package com.go.ssh.commons.web.intercepter;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.struts2.ServletActionContext;
import org.aspectj.lang.JoinPoint;

import com.go.ssh.commons.Constants;
import com.go.ssh.commons.exception.NoPrivilegeException;
import com.go.ssh.point.model.OperationRoleModel;
import com.go.ssh.point.model.UserModel;
import com.opensymphony.xwork2.ActionContext;

public class AuthenticationInterceptor {

	public void doBefore(JoinPoint jp) {
		// HttpServletRequest request = SessionToAop.getRequest();
		// HttpSession session = request.getSession(false);
		// UserModel user = (UserModel) session.getAttribute("userinfo");
		Map<String, Object> session = ActionContext.getContext().getSession();
		UserModel user = (UserModel) session
				.get(Constants.USER_INFO_SESSION_KEY);

		if (user == null)
			return;

		Map<String, Object> application = ServletActionContext.getContext()
				.getApplication();
		@SuppressWarnings("unchecked")
		List<OperationRoleModel> roles = (List<OperationRoleModel>) application
				.get(Constants.ROLE_MAP_KEY);

		String className = jp.getSignature().getDeclaringTypeName();
		String methodName = jp.getSignature().getName();
		boolean hasPrivilege = false;

		// TODO
		List<String> userRoles = new ArrayList<String>();
		if ("go".equals(user.getUsername())) {
			userRoles.add("admin");
			userRoles.add("account");
		} else {
			userRoles.add("anonymous");
		}

		for (OperationRoleModel role : roles) {
			if (role.getActionClassName().equals(className)
					&& role.getMethodName().equals(methodName)
					&& userRoles.contains(role.getRole())) {
				hasPrivilege = true;
				break;
			}
		}

		if (!hasPrivilege) {
			throw new NoPrivilegeException();
		}
	}
}
